<template>
  <div>
    <el-form :model="userInfo" label-width="100px">
      <el-form-item label="账号">
        <el-input v-model="userInfo.username" disabled />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="userInfo.name" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="userInfo.phone" />
      </el-form-item>
      <el-form-item label="电子邮箱">
        <el-input v-model="userInfo.email" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveInfo">保存信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request.js';
import { ElMessage } from 'element-plus';

const userInfo = ref({
  username: '',
  name: '',
  phone: '',
  email: '',
});

// 从 localStorage 获取用户名
const username = JSON.parse(localStorage.getItem('xm-pro-user'))?.username;

onMounted(async () => {
  if (username) {
    try {
      // 假设正确的接口地址是 '/api/user/getInfo'，请根据实际情况修改
      const apiUrl = '/user/getInfo'; 
      console.log('请求 URL:', `${apiUrl}?username=${username}`);
      const res = await request.get(apiUrl, { params: { username } });
      userInfo.value = res.data;
    } catch (error) {
      console.error('请求出错:', error);
      ElMessage.error('获取个人信息失败，请稍后重试');
    }
  } else {
    ElMessage.error('未获取到用户名，请重新登录');
  }
});

const saveInfo = async () => {
  try {
    
    await request.put('/user/updateInfo', userInfo.value); 
    ElMessage.success('信息保存成功');
  } catch (error) {
    ElMessage.error('信息保存失败，请稍后重试');
  }
};
</script>
<style scoped>
/* 可添加自定义样式 */
</style>